;
(function (call) {
    var main = {
        datepicker: null,
        dataList: null,
        isFirst: true,
        init: function () {
            this.bindEvt();
            this.initView();
        },
        initView: function () {
            var qbTime = new Date().format("yyyy-MM-dd hh:mm");
            this.datepicker = CafeJS.Datepicker({
                appendTo: "#qbTime",
                type: 1,
                dateType: "H",
                timeInterval: 12,
                customHm: [08, 20],
                dateFmt: "yyyy-MM-dd hh",
                curDate: qbTime
            });
            this.cfg.stations.forEach(function (station) {
                var $th = $('<th>');
                $th.html(station.name).data('id', station.id);
                $('.table-header tr').append($th);
            })
            $("#interval").find('li').eq(3).click();
            this.isFirst = false;
        },
        getData: function () {
            var that = this;
            var eleids = [],
                lons = [],
                lats = [],
                fcstTime,
                queryTime;
            var interval = Number($('#interval li.active').text());
            var endPeriod = Number($('#interval li.active').data('duration'));
            var elements = this.cfg.elements[interval] || this.cfg.elements['2'];

            elements.forEach(function (element) {
                eleids.push(element.id);
            })

            this.cfg.stations.forEach(function (station) {
                lons.push(station.lon);
                lats.push(station.lat);
            })
            if (that.isFirst) {
                var d = new Date();
                var hours = d.getHours();
                if (hours < 20) {
                    d.setDate(d.getDate() - 1);
                }
                queryTime = d.format('yyyy-MM-dd 20:00:00');
                this.datepicker.setVal(queryTime);
                fcstTime = d.format('yyyyMMdd200000');
            } else {
                queryTime = this.datepicker.getVal() + ':00';
                fcstTime = new Date(queryTime).format('yyyyMMddhh0000');
            }
            var params = {
                fcstTime: fcstTime, // 起报时间
                element: eleids.join(','),
                lon: lons.join(','),
                lat: lats.join(','),
                mode: 'GDMODE',
                startPeriod: 0,
                endPeriod: endPeriod, // 结束时效
                interval: interval, // 预报间隔
                count: 0,
                stationType: 3
            }
            loading.add('.cafe-container');
            $.getJSON(api.external.getGdybDataByParamData, params, function (res) {
                loading.remove();
                if (!res.success || !res.resultData) return;
                //that.dataList = res.resultData;
                that.dataList = that.reInitData(res.resultData);
                that.buildTableInfo();
            })
        },
        //重新构造数据结构
        reInitData:function(resultData){
            var that = this;
            var newData = [];
            var interval = Number($('#interval li.active').text());
            var endPeriod = Number($('#interval li.active').data('duration'));
            var elements = this.cfg.elements[interval] || this.cfg.elements['2'];
            that.cfg.stations.forEach(function (station) {
                var key = station.lon+"_"+station.lat;
                var date = that.datepicker.getVal() + ':00';
                var oldSingleData  = resultData[key];
                var periodData = [];
                for(var i = 1;i<=endPeriod/interval;i++){
                    var singperiod = {period:i * interval};
                    elements.forEach(function (element) {
                        var val = oldSingleData[element.id][0][i - 1];
                        val = Number(val)==9999?'--':val;
                        singperiod[element.id] = val;
                    })
                    periodData.push(singperiod);
                }
                newData.push({data:periodData,qbtime:date,stationId:station.id,updateTime:date});
            })
            return newData;
        },
        buildTableInfo: function () {
            var that = this;
            if (that.dataList.length === 0) return;

            var interval = Number($('#interval li.active').text()); // 时间间隔
            var elements = $('#element li.active') // 要素列表

            var timeList = []; // 时间列表
            var qbTime = new Date(that.dataList[0].qbtime); // 起报时间

            that.dataList[0].data.forEach(function (data) {
                var d = new Date(qbTime);
                d.setHours(qbTime.getHours() + Number(data.period));
                timeList.push(d.format('yyyy-MM-dd hh:00'));
            })
            /*
            if (interval == 6 || interval == 12) {
                var tempData = {};
                that.dataList.forEach(function (data, i) {
                    data.data.forEach(function (item, j) {
                        if ((j + 1) % 2 !== 0 || (j + 1) % 4 !== 0) {
                            if (interval == 6 && (j + 1) % 4 !== 0)
                                tempData = data.data[(parseInt((j + 1) / 4) + 1) * 4 - 1];
                            else if (interval == 12 && (j + 1) % 2 !== 0)
                                tempData = data.data[(parseInt((j + 1) / 2) + 1) * 2 - 1];
                            item.RHMIN = tempData.RHMIN;
                            item.RHMAX = tempData.RHMAX;
                            item.TCCMIN = tempData.TCCMIN;
                            item.TCCMAX = tempData.TCCMAX;
                            item.TMIN = tempData.TMIN;
                            item.TMAX = tempData.TMAX;
                            item.VISMIN = tempData.VISMIN;
                        }
                    })
                })
            }
            */
            var $trs = [],
                $table = $('.table-body table').empty(),
                tdWidth = ($('.table-header').width() * (90 / (that.cfg.stations.length + 1))) / 100;
            tdWidth = Math.floor(tdWidth) - 1;

            timeList.forEach(function (time, i) { // 时间列表
                elements.each(function (j, element) { // 要素列表
                    var $tr = $('<tr>'),
                        $tds = [];
                    if (j === 0) { // 时间跨行
                        var ybTime = new Date(time).format('MM月dd日hh时');
                        if (interval > 1) {
                            var endDate = new Date(time);
                            var startDate = new Date(time);
                            startDate.setHours(startDate.getHours() - interval);
                            if (endDate.getFullYear() != startDate.getFullYear())
                                ybTime = startDate.format('yyyy年MM月dd日hh时') + ' - ' + endDate.format('yyyy年MM月dd日hh时')
                            if (endDate.getDate() != startDate.getDate())
                                ybTime = startDate.format('MM月dd日hh时') + ' - ' + endDate.format('MM月dd日hh时')
                            else
                                ybTime = startDate.format('MM月dd日hh时') + ' - ' + endDate.format('hh时')
                        }

                        $tds.push('<td rowspan=' + elements.length + ' class=time>' + ybTime + '</td>');
                    }
                    $tds.push('<td>' + $(element).data('element').name + $(element).data('element').unit + '</td>');
                    that.cfg.stations.forEach(function (station) { // 站点列表
                        that.dataList.forEach(function (data, k) {
                            if (station.id == data.stationId) {
                                var val = that.dataList[k].data[i][$(element).data('element').id];
                                if (val !== 0)
                                    val = val || ' ';
                                $tds.push('<td title=' + val + '><span style="width: ' + tdWidth + 'px">' + val + '</span></td>');
                                return false;
                            }
                        })
                    })
                    $trs.push($tr.html($tds.join('')));
                })
            })
            $table.append($trs);
        },
        //点击显示pdf技术说明
        showTechPdf: function () {
            var id = 'techPfd';
            if (CafeJS.ModalBoxExist(id)) {
                CafeJS.ModalBoxShow(id);
                return;
            }
            CafeJS.ModalBox({
                id: id,
                container: 'rainfall-container',
                title: "技术说明",
                width: 1300,
                height: 700,
                m_top: 70,
                m_right: 90,
                hasMask: true,
                hide: true,
                html: "<div id='" + id + "' style='width:100%;height:calc(100% - 10px)'></div>",
                showCall: function () {
                    PDFObject.embed('/business/common/pdf/新版滚动服务产品.pdf', "#" + id);
                },
                closed: function () { }
            });
        },
        bindEvt: function () {
            var that = this;
            $("#interval").on("click", 'li', function () {
                $(this).addClass("active").siblings().removeClass("active");

                var interval = Number($(this).text());
                var elements = that.cfg.elements[interval] || that.cfg.elements['2'];

                if (elements.length == $('#element li').length) {
                    that.getData();
                    return;
                }

                $('#element').empty();
                elements.forEach(function (element) {
                    var $li = $('<li>');
                    $li.html(element.name);
                    $li.data('element', element);
                    $li.addClass('active');
                    $('#element').append($li);
                })
                that.getData();
            })
            $("#element").on("click", 'li', function () {
                if ($(this).hasClass('active')) {
                    $(this).removeClass("active");
                } else {
                    $(this).addClass("active");
                }
            })
            $('#queryBtn').click(function () {
                that.getData();
            })
            $("#downBtn").click(function () {
                $.exportExcel({
                    tableId: 'tableInfo',
                    tableNm: '滚动预报' + new Date().format('yyyyMMddhhmmss')
                })
            })
            $('#techpdf').click(function () {
                that.showTechPdf();
            })
        },
        cfg: {
            stations: [
                { name: '天津市区', id: '54517', lon: 117.21, lat: 39.07 },
                { name: '蓟州', id: '54428', lon: 117.45, lat: 40.05 },
                { name: '宝坻', id: '54525', lon: 117.28, lat: 39.73 },
                { name: '武清', id: '54523', lon: 117.06, lat: 39.43 },
                { name: '宁河', id: '54529', lon: 117.85, lat: 39.38 },
                { name: '静海', id: '54619', lon: 116.92, lat: 38.93 },
                { name: '北辰', id: '54528', lon: 117.14, lat: 39.24 },
                { name: '西青', id: '54527', lon: 117.05, lat: 39.08 },
                { name: '津南', id: '54622', lon: 117.42, lat: 38.95 },
                { name: '东丽', id: '54526', lon: 117.34, lat: 39.08 },
                { name: '滨海新区', id: '54623', lon: 117.79, lat: 39.16 }
            ],
            elements: {
                "1": [
                    { id: 'WEA', name: '天气现象', unit: '' },
                    { id: 'TMP', name: '气温', unit: '(℃)' },
                    { id: 'EDA', name: '风', unit: '' },
                    { id: 'RH', name: '湿度', unit: '(%)' },
                    { id: 'TCC', name: '云量', unit: '(%)' },
                    { id: 'VIS', name: '能见度', unit: '(km)' },
                    { id: 'TP1H', name: '降水量', unit: '(mm)' }
                ],
                "2": [
                    { id: 'WEA', name: '天气现象', unit: '' },
                    { id: 'TMAX', name: '最高温', unit: '(℃)' },
                    { id: 'TMIN', name: '最低温', unit: '(℃)' },
                    { id: 'EDA', name: '风', unit: '(mm)' },
                    { id: 'RHMAX', name: '最高湿度', unit: '(%)' },
                    { id: 'RHMIN', name: '最低湿度', unit: '(%)' },
                    { id: 'TCCMAX', name: '最高云量', unit: '(%)' },
                    { id: 'TCCMIN', name: '最低云量', unit: '(%)' },
                    { id: 'VISMIN', name: '最低能见度', unit: '(km)' },
                    { id: 'TP1H', name: '降水量', unit: '(mm)' }
                ]
            }
        }
    };
    if (typeof call === 'function') {
        call(main);
    }
})(function (main) {
    CafeJS.models(['navigationmenu', 'cafe-datepicker', 'cafeMap', 'moddialog'], function(navMenu) {
        main.init(navMenu);
        window.alert = function (info) {
            $.dialogMaster({
                "type": 'tip',
                "info": info
            });
        }
    });

})